/**
 *
 * 键盘漫游
 * @param     viewer             Mars3d实例对象
 * @param     moveForward        前(按键)
 * @param     moveBackward       后(按键)
 * @param     moveLeft           左(按键)
 * @param     moveRight          右(按键)
 * @param     moveUp             上(按键)
 * @param     moveDown           下(按键)
 * 
 * @returns  BQGIS_RoamingKey
 *
 */



/**
 * 默认键盘操作事件
 */
let keyOption = {
    moveForward:"w",
    moveBackward:"s",
    moveLeft:"a",
    moveRight:"d",
    moveUp:"q",
    moveDown:"e"
}
export function BQGIS_initRoamingByKey(option){
    keyOption = Object.assign(keyOption,option.key)
    return new BQGIS_RoamingKey(option.viewer)
}

function BQGIS_RoamingKey(viewer){
    this.status = "init" // doing stop
    this.handler = null
    this.viewer = viewer
    viewer = viewer
}

let flags = {}
// 渲染函数 所用的viewer
let viewer
BQGIS_RoamingKey.prototype.start = function start(){
    this.status = "doing"
    let scene = this.viewer.scene
    let canvas = this.viewer.canvas
    // 禁止相机默认行为
    scene.screenSpaceCameraController.enableRotate = false;
    scene.screenSpaceCameraController.enableTranslate = false;
    scene.screenSpaceCameraController.enableZoom = false;
    scene.screenSpaceCameraController.enableTilt = false;
    scene.screenSpaceCameraController.enableLook = false;

    flags = {
        looking: false, // 是否正在用鼠标调整视角
        startPosition: null, // 鼠标指针开始移动位置
        endPosition: null, // 鼠标指针停止移动位置
        moveForward: false, // 是否向前移动
        moveBackward: false, // 是否向后移动
        moveLeft: false, // 是否向左移动
        moveRight: false, // 是否向右移动
        moveUp: false, // 是否向上移动
        moveDown: false, // 是否向下移动
    }

    this.handler = new Cesium.ScreenSpaceEventHandler(canvas);

    // 左键按下
    this.handler.setInputAction((movement) => {
        flags.looking = true;
        flags.startPosition = Cesium.Cartesian3.clone(movement.position);
        flags.endPosition = Cesium.Cartesian3.clone(movement.position);
    }, Cesium.ScreenSpaceEventType.LEFT_DOWN);
    // 鼠标移动
    this.handler.setInputAction((movement) => {
        flags.endPosition = movement.endPosition;
    }, Cesium.ScreenSpaceEventType.MOUSE_MOVE);
    // 左键弹起
    this.handler.setInputAction(() => {
        flags.looking = false;
    }, Cesium.ScreenSpaceEventType.LEFT_UP);

    // 4.添加键盘监听事件
    // 键盘按下事件
    document.addEventListener('keydown', keyDown, false);
    // 键盘弹起事件
    document.addEventListener('keyup', keyUp, false);

    viewer = this.viewer
    // 5.添加渲染事件
    this.viewer.clock.onTick.addEventListener(renderEvent);
}

BQGIS_RoamingKey.prototype.stop = function stop(){
    if (this.handler) {
        this.status = "stop"
        this.handler.destroy();
        this.handler = null;
      }
    
      // 2.移除键盘监听事件
      document.removeEventListener('keydown', keyDown, false);
      document.removeEventListener('keyup', keyUp, false);
    
      // 3.移除渲染事件
      this.viewer.clock.onTick.removeEventListener(renderEvent);
    
      // 4.启用默认相机操作模式
      let scene = this.viewer.scene
      scene.screenSpaceCameraController.enableRotate = true;
      scene.screenSpaceCameraController.enableTranslate = true;
      scene.screenSpaceCameraController.enableZoom = true;
      scene.screenSpaceCameraController.enableTilt = true;
      scene.screenSpaceCameraController.enableLook = true;
}
// 更新操作
BQGIS_RoamingKey.prototype.updateOption = function updateOption(option){
  this.viewer = option.viewer || this.viewer
  keyOption = Object.assign(keyOption,option.key)
}


function operationByKeyCode(keyCode){
  
  keyCode = keyCode.toLowerCase()
  let k
  for(k in keyOption){
    if(keyCode == keyOption[k]) return k
  }
  return ""
}

function keyDown(evt){
  let keyOptionKey = operationByKeyCode(evt.key)
  if(keyOptionKey!=="")flags[keyOptionKey] = true;
}

function keyUp(evt){
    let keyOptionKey = operationByKeyCode(evt.key)
    if(keyOptionKey!=="")flags[keyOptionKey] = false;
}

/**
 * 渲染函数
 */
function renderEvent() {
  if(!viewer) return console.warn("viewer:" + viewer)
  let camera = viewer.camera;
  let ellipsoid = viewer.scene.globe.ellipsoid;
  // 镜头转向
  if (flags.looking) {
    let width = viewer.canvas.clientWidth;
    let height = viewer.canvas.clientHeight;
    let lookFactor = 0.05; // 镜头转向系数，系数越大约灵敏，此处取0.05比较适中
    let x = (flags.endPosition.x - flags.startPosition.x) / width;
    let y = -(flags.endPosition.y - flags.startPosition.y) / height;
    // 计算出x,y之后，有两种方式实现镜头，经过测试感觉方式 1更流畅
    // 方式 1
    camera.lookRight(x * lookFactor);
    camera.lookUp(y * lookFactor);
    // 方式 2
    // camera.setView({
    //   orientation: {
    //     heading: camera.heading + x * lookFactor,
    //     pitch: camera.pitch + y * lookFactor,
    //     roll: 0.0,
    //   },
    // });
  }
  // 根据高度来决定镜头移动的速度
  let cameraHeight = ellipsoid.cartesianToCartographic(camera.position).height;
  let moveRate = cameraHeight / 100.0;
  cameraAnimal(camera,moveRate)
}
function cameraAnimal(camera,moveRate){
  // 前进
  if (flags.moveForward) camera.moveForward(moveRate);
  // 后退
  if (flags.moveBackward) camera.moveBackward(moveRate);
  // 视角上移
  if (flags.moveUp) camera.moveUp(moveRate);
  // 视角下移
  if (flags.moveDown) camera.moveDown(moveRate);
  // 视角左移
  if (flags.moveLeft) camera.moveLeft(moveRate);
  // 视角右移
  if (flags.moveRight) camera.moveRight(moveRate);
}